package io.gitee.hefren.hhcache.core;

import com.google.common.base.Strings;
import io.gitee.hefren.hhcache.conf.HhPlugin;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Date 2024/6/30
 * @Author lifei
 */
@Component
public class HhCacheServer implements HhPlugin {

    private static final int PORT = 6379;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workGroup;
    private Channel serverChannel;

    @Override
    public void init() {
        // 用于产生 ServerChannel 的 EventLoop
        bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("hhcache-boss"));
        // 用于产生 Channel 的EventLoop
        workGroup = new NioEventLoopGroup(16, new DefaultThreadFactory("hhcache-work"));
    }

    @Override
    public void startup() {

        try {

            ServerBootstrap bootstrap = new ServerBootstrap();
            // 关联 bossGroup 和 workGroup
            bootstrap.group(bossGroup, workGroup)
                    // 指定 serverchannel的类型
                    .channel(NioServerSocketChannel.class)
                    // 给 serverChannel 的 channelPipeline 创建 handler
                    .handler(new LoggingHandler(LogLevel.ERROR))
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            // @TODO 关联业务相关的 handler
                            channel.pipeline().addLast(new HhCacheDecoder(), new HhCacheHandler());
                        }
                    })
                    // 给serverChannel添加配置
                    .option(ChannelOption.SO_BACKLOG, 128) // 队列长度
                    // 给 channel 添加配置
                    .childOption(ChannelOption.SO_KEEPALIVE, true) // 保持长连接
                    .childOption(ChannelOption.SO_RCVBUF, 32 * 1024) // 接收字节的缓存大小
                    .childOption(ChannelOption.SO_SNDBUF, 32 * 1024) // 发送字节的缓存大小
                    .childOption(ChannelOption.TCP_NODELAY, true) // 小包也立马发送
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) // byteBuf 优化策略
                    .childOption(ChannelOption.SO_REUSEADDR, true) // 复用端口
                    .childOption(EpollChannelOption.SO_REUSEPORT, true)
            ;
            serverChannel = bootstrap.bind(PORT).sync().channel();
            System.out.println(Strings.lenientFormat("===> HhCacheServer started, listening on port %s", PORT));
            // 等待它关闭
            serverChannel.closeFuture().sync();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }


    }

    @Override
    public void shutdown() {
        if (Objects.nonNull(serverChannel)) {
            serverChannel.close();
            serverChannel = null;
        }
        if (Objects.nonNull(bossGroup)) {
            bossGroup.shutdownGracefully();
            bossGroup = null;
        }
        if (Objects.nonNull(workGroup)) {
            workGroup.shutdownGracefully();
            workGroup = null;
        }
    }
}
